package com.myframework.listeners.jsflisteners;

import javax.faces.application.Application;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

import com.webmeeting.chat.wordchat.dao.entities.User;

public class PermissionPhaseListener implements PhaseListener {

	private static final long	serialVersionUID	= 1L;

	@Override
	public void afterPhase(PhaseEvent event) {
		// Do nothing here
	}

	/**
	 * Check the permission of user in <strong>PhaseId.RESTORE_VIEW</strong> phase
	 */
	@Override
	public void beforePhase(PhaseEvent event) {
		FacesContext currContext = FacesContext.getCurrentInstance();
		HttpSession currSession = (HttpSession) currContext.getExternalContext().getSession(true);
		User currUser = (User) currSession.getAttribute("user");
		if (null == currUser) {
			gotoNoPermissionPage();
		}
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RENDER_RESPONSE;
	}

	private void gotoNoPermissionPage() {
		FacesContext currContext = FacesContext.getCurrentInstance();
		Application application = currContext.getApplication();
		NavigationHandler navHandler = application.getNavigationHandler();
		navHandler.handleNavigation(currContext, null, currContext.getExternalContext().getRequestContextPath() + "/login.xhtml");
	}

}
